﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using StyleMVVM.DependencyInjection;
using StyleMVVM.WCF.LanguageExtensions;

namespace StyleMVVM.WCF.DependencyInjection
{
	public class WCFSharedPerRequestContainer : ILifeCycleContainer
	{
		private Guid key;

		public WCFSharedPerRequestContainer()
		{
			key = Guid.NewGuid();
		}

		public object RetrieveObject(IExportStrategy strategy,
		                             ExportLifeCycleMethod exportMethod,
		                             IDependencyInjectionContainer container,
		                             IInjectionContext injectionContext,
		                             object[] constructorParams)
		{
			IDictionary<object, object> items = OperationContext.Current.Items();
			object returnValue = items[key];

			if (returnValue == null)
			{
				IDisposalScope oldScope = null;
				IDisposalScope newScope = null;

				if (!strategy.ExternallyOwned)
				{
					oldScope = injectionContext.DisposalScope;

					newScope = OperationContext.Current.DisposalScope();

					injectionContext.DisposalScope = newScope;
				}
				
				returnValue = exportMethod(injectionContext, constructorParams);

				if (oldScope != null)
				{
					injectionContext.DisposalScope = oldScope;
				}

				IDisposable disposable = returnValue as IDisposable;

				if (disposable != null && newScope != null)
				{
					newScope.AddObject(disposable);
				}

				items[key] = returnValue;
			}

			return returnValue;
		}

		public void Shutdown()
		{
			
		}
	}
}